﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

//将TextArea的skin,边框都设置空.
public class GUIInput : MonoBehaviour {
	// Use this for initialization
	public Camera cam;
	public string text;
	
	public float bgWidth = 300;
	public float bgHeight = 30;
	
	public bool afterEnterClear = true;
	public UITextList textList;
	
	public GameObject eventGo;
	public string functionName = "OnGUIInputEnter";
	
	public KeyCode sendKey = KeyCode.Return; //发送的按键
	public bool useControl; //发送时 是否使用control
	
	//要使用的皮肤
	public GUISkin skin;
	
	private Vector2 scrollPos;
	private Rect startRect = new Rect(100,100,300,200);
	// public Rect textAreaRect;
	private Vector2 lineWidthHeight = Vector2.zero;
	void Start(){
		
	}
	
	void Update() {
		Vector3 pos = cam.WorldToScreenPoint(transform.position);
		startRect = new Rect(pos.x - bgWidth * 0.5f,(Screen.height-pos.y)-bgHeight*0.5f,bgWidth,bgHeight);
	}
	
	void OnGUI(){
		///样式
		GUI.skin = skin;
		//上下左右边界清零.
		GUI.skin.textArea.padding = new RectOffset(0,0,0,0);
		GUI.skin.textArea.normal.background = null;
		GUI.skin.textArea.onNormal.background = null;
		GUI.skin.textArea.hover.background = null;
		GUI.skin.textArea.onHover.background = null;
		///绘制
		GUILayout.BeginArea(startRect);
			//绘制背景
			GUI.Box(new Rect(0,0,startRect.width,startRect.height),"");
			//绘制滚动.
			scrollPos = GUILayout.BeginScrollView(scrollPos);
				GUI.SetNextControlName("textArea");
				text = GUILayout.TextArea(text);
			GUILayout.EndScrollView();
		GUILayout.EndArea();
		
		///事件
		Event e = Event.current;
		//处理键盘
		HandleKey(e);
		//处理鼠标
		handleMouse(e);
		//用来计算每行的高度.
		if(lineWidthHeight == Vector2.zero)
			lineWidthHeight = GUI.skin.textArea.CalcSize(new GUIContent("a"));
		//处理滚动.
		Scroll(e);
	}
	//处理键盘
	void HandleKey(Event e){
		if(e.isKey){
			if(useControl){
				if(e.control && e.keyCode == KeyCode.Return){
					Send();
				}
			}else{
				if(e.keyCode == KeyCode.Return){
					Send();
				}
			}
		}		
	}
	//处理鼠标
	void handleMouse(Event e){
		if(e.isMouse && e.button == 0){
			if(startRect.Contains(e.mousePosition)){
				GUI.FocusControl("textArea");
			}
		}
	}
	//滚动.
	void Scroll(Event e){
		if(e.isKey){
			if(e.keyCode == KeyCode.Return)
				scrollPos = new Vector2(scrollPos.x,scrollPos.y + lineWidthHeight.y);	
			else if(e.keyCode == KeyCode.UpArrow)
				scrollPos = new Vector2(scrollPos.x,scrollPos.y - lineWidthHeight.y);
			else if(e.keyCode == KeyCode.DownArrow)
				scrollPos = new Vector2(scrollPos.x,scrollPos.y + lineWidthHeight.y);
		}
	}
	//发送 字符
	void Send(){
		if(textList != null){
			textList.Add(text);
		}
		if(eventGo != null)
			eventGo.SendMessage(functionName,text,SendMessageOptions.DontRequireReceiver);
		text = "";		
	}

}